/* eslint-disable prefer-destructuring */
/**
 * Created by mar105 on 2019-03-27.
 */
import React, { Component } from 'react';
import { Modal, message } from 'antd';
import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonFunc from './commonFunc'; /* 通用单据方法 */
import * as commonConfig from '../../utils/config';
import * as commonServices from '../../services/services'; /*   服务类   */

const { confirm } = Modal;

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {};
    }

    componentWillReceiveProps(nextProps) {
      const {
        formData, currentId, searchSolution, masterData,
      } = nextProps;
      let { slaveColumn } = nextProps;
      if (commonUtils.isEmptyArr(slaveColumn) && formData.length > 0) {
        const sId = currentId !== undefined ? currentId : '';
        /* 数据Id */
        const slaveConfig = formData[0];
        slaveColumn = commonFunc.getHeaderConfig(slaveConfig);
        let filterCondition = [];
        if (commonUtils.isNotEmptyObject(masterData) && !commonUtils.isEmpty(masterData.sSearchSolutionId) && commonUtils.isNotEmptyArr(searchSolution)) {
          const iIndex = searchSolution.findIndex(item => item.sId === masterData.sSearchSolutionId);
          if (iIndex > -1 && !commonUtils.isEmpty(searchSolution[iIndex].sCondition)) {
            filterCondition = JSON.parse(searchSolution[iIndex].sCondition);
          }
        }
        this.handleGetData(slaveConfig, filterCondition, 1);
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnFirst', sControlName: 'BtnFirst',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnFirst', sControlName: 'BtnPrior',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnFirst', sControlName: 'BtnNext',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnFirst', sControlName: 'BtnLast',
        });
        this.props.onSaveState({
          masterConfig: slaveConfig, slaveConfig, slaveColumn, sId, pageLoading: false,
        });
      }
    }

    shouldComponentUpdate(nextProps) {
      const { slaveColumn } = nextProps;
      return commonUtils.isNotEmptyArr(slaveColumn);
    }

    /**   获取表数据   */
    handleGetData = (slaveConfig, slaveFilterCondition, page, slaveOrderBy) => {
      this.props.handleGetDataSet({
        name: 'slave',
        configData: slaveConfig,
        condition: {
          pageNum: page, pageSize: commonConfig.pageSize, bFilter: slaveFilterCondition, sFilterOrderBy: slaveOrderBy,
        },
      });
    };

    handleTitleChange = (slavePagination, filters, sorter) => {
      const { slaveConfig, slaveFilterCondition } = this.props;
      const sort = sorter.order === 'ascend' ? 'asc' : 'desc';
      const slaveOrderBy = Object.keys(sorter).length > 0 ? { [sorter.columnKey]: sort } : ''; // 后端未支持空对象， 先用空表示
      this.handleGetData(slaveConfig, slaveFilterCondition, slavePagination.current, slaveOrderBy);
    };

    handleDoubleClick = (record) => {
      const {
        slaveConfig, slaveData, dispatch, slaveFilterCondition, slavePagination, slaveOrderBy,
      } = this.props;
      const picArr = slaveConfig.gdsconfigformslave.filter(item => (item.sName === 'picArr'));
      if (picArr.length > 0) {
        let sActiveId = '';
        if (picArr[0].sName === 'picArr' && picArr[0].sDropDownType === 'picArr') {
          [{ sActiveId }] = picArr;
        }
        const sNameUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`;
        dispatch({
          type: 'content/onRouter',
          payload: {
            refresh: this.handleGetData.bind(this, slaveConfig, slaveFilterCondition, slavePagination.current, slaveOrderBy), /*   刷新方法   */
            url: sNameUrl,
            sTabId: commonUtils.createSid(),
            sParentId: this.state.sTabId,
            urlDataType: 'newPane',
            checkedId: record.sId,
            bFilter: slaveFilterCondition,
            pageSize: commonConfig.pageSize,
            pages: slavePagination,
            currentData: slaveData,
            sListFormmasterId: slaveConfig.sId,
            newKey: record.sId,
            currentIndex: slaveData.findIndex(item => item.sId === record.sId),
          },
        });
      }
    };

    /**   表单回带   */
    handleForm = (form) => {
      this.form = form;
    };

    /**  点击新增按钮   */
    handleAdd = () => {
      const {
        slaveConfig, slaveData, dispatch, slaveFilterCondition, slavePagination, slaveOrderBy,
      } = this.props;
      const picArr = slaveConfig.gdsconfigformslave.filter(item => (item.sName === 'picArr'));
      if (picArr.length > 0) {
        let sActiveId = '';
        if (picArr[0].sName === 'picArr' && picArr[0].sDropDownType === 'picArr') {
          [{ sActiveId }] = picArr;
        }
        const sNameUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`;
        dispatch({
          type: 'content/onRouter',
          payload: {
            refresh: this.handleGetData.bind(this, slaveConfig, slaveFilterCondition, slavePagination.current, slaveOrderBy), /*   刷新方法   */
            url: sNameUrl,
            sTabId: commonUtils.createSid(),
            sParentId: this.state.sTabId,
            urlDataType: 'newPane',
            bFilter: slaveFilterCondition,
            pageSize: commonConfig.pageSize,
            pages: slavePagination,
            currentData: slaveData,
            sListFormmasterId: slaveConfig.sId,
          },
        });
      }
    };

    /* 确定要删除 */
    handleOkDel = async (props) => {
      /*   数据参数   */
      const {
        token, sModelsId, slaveConfig, slaveData, slaveSelectedRowKeys, slaveFilterCondition, slavePagination, slaveOrderBy,
      } = props;
      const allId = [];
      slaveSelectedRowKeys.forEach((key) => {
        const iIndex = slaveData.findIndex(item => item.sSlaveId === key);
        if (iIndex > -1) {
          if (allId.indexOf(slaveData[iIndex].sId) === -1) {
            allId.push(slaveData[iIndex].sId);
          }
        }
      });
      if (commonUtils.isNotEmptyArr(allId)) {
        const value = {
          sClientType: '1',
          data: {
            sMasterTable: slaveConfig.sTbName,
            sId: allId,
            sSlaveTable: 'commonList',
          },
        };
        const url = `${commonConfig.server_host}business/delMasSlaBusinessData?sModelsId=${sModelsId}`;
        /*   接收返回值   */
        const { data } = await commonServices.postValueService(token, value, url);
        if (data.code === 1) {
          /*   数据删除成功   */
          message.success(data.msg);
          this.props.handleGetDataSet({
            name: 'slave',
            configData: slaveConfig,
            condition: {
              pageNum: slavePagination.current, pageSize: commonConfig.pageSize, bFilter: slaveFilterCondition, slaveOrderBy,
            },
          });
        } else { /*   失败   */
          this.props.getServiceError(data);
        }
      }
    };

    handleDel = () => {
      const onOkDel = this.handleOkDel;
      const props = this.props;
      confirm({
        title: commonFunc.showMessage(props.app.commonConst, 'SureDel'),
        onOk() {
          onOkDel(props);
        },
        onCancel() {},
      });
    }

    /* 导出Excel */
    handleOut = () => {
      const { slaveConfig, slaveFilterCondition, slaveOrderBy } = this.props;
      let url = `${commonConfig.server_host}excel/export/${slaveConfig.sId}?sModelsId=${slaveConfig.sParentId}&token=${this.props.app.token}`;
      if (commonUtils.isNotEmptyArr(slaveFilterCondition)) {
        url = `${url}&bFilter=${encodeURIComponent(JSON.stringify(slaveFilterCondition))}`;
      }
      if (slaveOrderBy !== undefined && slaveOrderBy !== '' && Object.keys(slaveOrderBy).length > 0) {
        url = `${url}&sFilterOrderBy=${encodeURIComponent(JSON.stringify(slaveOrderBy))}`;
      }
      window.open(url);
    };

    /** 按钮操作事件 */
    handleButtonClick = (name) => {
      if (name === 'BtnOut') {
        this.handleOut();
      } else if (name === 'BtnRefresh') {
        const {
          slaveConfig, slavePagination, slaveFilterCondition, slaveOrderBy,
        } = this.props;
        this.handleGetData(slaveConfig, slaveFilterCondition, slavePagination.current, slaveOrderBy); /*   刷新方法   */
      }
    }

    /*   单据页复制到   */
    handleCopyTo = (name, sActiveId) => {
      /*   待用数据声明   */
      const {
        dispatch, slaveConfig, slaveSelectedData, slavePagination, app, slaveFilterCondition, slaveOrderBy,
      } = this.props;
      if (commonUtils.isNotEmptyArr(slaveSelectedData)) {
        const copyTo = {};
        const copyToConfig = slaveConfig.gdsconfigformslave.filter(item => item.sControlName.includes(name));
        const copyToData = slaveSelectedData;

        // 不重复字段处理 例如 复制到时只能同一客户复制到
        const iIndex = copyToConfig.findIndex(item => item.sControlName === name);
        if (iIndex > -1 && !commonUtils.isEmpty(copyToConfig[iIndex].sNotRepeatColumn)) {
          const sNotRepeatColumn = copyToConfig[iIndex].sNotRepeatColumn.trim();
          const sNotRepeatValue = copyToData[0][sNotRepeatColumn];
          const iCount = copyToData.filter(item => item[sNotRepeatColumn] === sNotRepeatValue).length;
          if (iCount !== copyToData.length) {
            const iConfigIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === sNotRepeatColumn);
            const sNotRepeatShowName = iConfigIndex > -1 ? slaveConfig.gdsconfigformslave[iConfigIndex].showName : '';
            message.warn(commonFunc.showMessage(app.commonConst, 'pleaseChooseSame') + sNotRepeatShowName); // 请选择相同
            return;
          }
        }

        if (commonUtils.isNotEmptyArr(copyToData)) {
          copyTo.name = name;
          copyTo.config = copyToConfig;
          copyTo.masterData = copyToData[0];
          copyTo.slaveData = copyToData;
          dispatch({
            type: 'content/onRouter',
            payload: {
              url: `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`, /*   接口地址   */
              copyTo,
              refresh: this.handleGetData(slaveConfig, slaveFilterCondition, slavePagination.current, slaveOrderBy),
            },
          });
        } else {
          message.warn(commonFunc.showMessage(app.commonConst, 'pleaseChooseData')); // 请选择数据
        }
      } else {
        message.warn(commonFunc.showMessage(app.commonConst, 'pleaseChooseData')); // 请选择数据
      }
    };

    render() {
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onReturnForm={this.handleForm}
          onGetData={this.handleGetData}
          onTitleChange={this.handleTitleChange}
          onDoubleClick={this.handleDoubleClick}
          onAdd={this.handleAdd}
          onDel={this.handleDel}
          onButtonClick={this.handleButtonClick}
          onCopyTo={this.handleCopyTo}
        />
      );
    }
  };
};
